﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows.Forms;

namespace MineCraft_Update
{
    public partial class Form1 : Form
    {
        
        public Boolean bitquestion;
        public DirectoryInfo baseDirectory;
        public int selection = 1;
        //private string SVNDIR = "./SlikSvn/bin";
        private string SVNName = "SlikSvn";
        private string SVN64 = "http://www.sliksvn.com/pub/Slik-Subversion-1.7.4-x64.msi";
        private string SVN32 = "http://www.sliksvn.com/pub/Slik-Subversion-1.7.4-win32.msi";
        private string minecraftDIR = "";
        private string settingsDIR = "";
        private string settingsFile = "";
        private string settings_sync_File = "";
        private string minecraft_update_client_dir = "";
        private string minecraft_update_client_exe = "";
        private string minecraft_exe = "";
        private IPAddress serverIP;
        private readonly IDictionary<string, IPAddress> servers;
        private string username = "username";
        private string password = "password";
        const string quote = "\"";
        /*private Repository repository_clientfiles = GitSharp.Git.Clone(new CloneCommand
        {
            Source = "https://code.google.com/r/tynjcool-latest-release/", 
            GitDirectory = Environment.GetEnvironmentVariable("appdata") + "./.minecraft_update_client", 
            Quiet = false, 
            Bare = true });*/
        private string Repo = "\"https://jessica-minecraft-server.googlecode.com/svn/trunk/Client_Files/\"";
        private string Repo_MCU_client = "\"https://jessica-minecraft-server.googlecode.com/svn/trunk/.minecraft_update_client/\"";
        private Boolean Svn_status = false;
        //public event Form_Event Event; //======================== Link The SetIPEvent1 in Form1
        public Form1()
        {
            InitializeComponent();

            servers = new Dictionary<string, IPAddress>();

            //GitSharp.Git.Clone("https://code.google.com/p/jessica-minecraft-serverfiles/client_files", Environment.GetEnvironmentVariable("appdata") + "./.minecraft_update_client");
            //Repository repository_clientfiles = new Repository("https://Tynjcool@code.google.com/r/tynjcool-latest-release/ ");
            

            bitquestion = System.Environment.Is64BitOperatingSystem;
            osname.Text = Environment.OSVersion.ToString();
            minecraftDIR = FindMinecraft();


            //Branch.Create(Repository repo, string name, Commit commit)
            
            

            ConsoleLog("Welcome to Easy Life \n");

//            MainWork.DoWork += new DoWorkEventHandler(MainWork_Do.MainWork_DoWork);

//            MainWork.RunWorkerAsync("nom");


//            backwork.DoWork += new DoWorkEventHandler(MainWorker_DoWork);

            //ConsoleLog(
                //readable_delete2(
                //Log_Readable_list(run_command_SVNlog("svn log " + FindMinecraft()))));

            writelog(run_command_SVNlog("svn log " + Repo ));

            //Git.Clone(new CloneCommand { Source = "git://github.com/henon/GitSharp.git", GitDirectory = "path/to/local/copy", Quiet = false, Bare = true });

            //ConsoleLog( readable_delete2( + " \n " + readable_delete2(run_command_SVNlog("svn log " + FindMinecraft())[1]));

            MainStartup();

            MainFunction();
        }

        private Boolean Main_update_function()
        {
  //          string appPath = Path.GetDirectoryName(Application.ExecutablePath);
            if (File.Exists(minecraft_update_client_exe))
            {
                FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(Application.ExecutablePath);
                FileVersionInfo myFileVersionInfo_other = FileVersionInfo.GetVersionInfo(minecraft_update_client_exe);
                if (minecraft_update_folder_exist())
                {
                    int version_difference = new Version(myFileVersionInfo.FileVersion).CompareTo(new Version(myFileVersionInfo_other.FileVersion));
                    Console.WriteLine("Our version {0} is older then {1}", myFileVersionInfo.FileVersion, myFileVersionInfo_other.FileVersion);
                    Console.WriteLine("ours.CompareTo.theres {0}", version_difference);
                    if (version_difference < 0)
                    {
                        Console.WriteLine("(Updating Program) Our version {0} is older then {1}", myFileVersionInfo.FileVersion, myFileVersionInfo_other.FileVersion);
                        ShowUpdates();
                    }
                }
            }
            else
            {
                Console.WriteLine("The update MineCraft Update does not exist");
            }
            return false;
        }

        private void MainStartup()
        {

            if (Minecraft_Exist())
            {
                if (username_box.Text == "") { username_box.Text = "username"; }
                if (password_box.Text == "") { password_box.Text = "password"; password_box.UseSystemPasswordChar = false; }
                settingsDIR = minecraftDIR + "/config/settings";
                settingsFile = settingsDIR + "/MineCraft_Updater_Settings.cfg";
                settings_sync_File = settingsDIR + "/SVN_Sync_settings.jes";


                if (minecraft_update_folder_exist()) {
//                    Console.WriteLine("Location : {0}", minecraft_update_client_dir);
                    minecraft_update_client_exe = minecraft_update_client_dir + "/MineCraft Update.exe"; 
                }

                minecraft_exe = settingsDIR + "/minecraft.exe";
                toolTip1.SetToolTip(advanced_login_checkbox, "This is used to start minecraft with your credential at the end \n MineCraft.exe username password");
                toolTip2.SetToolTip(fast_start, "This will make the program run the update command at start for faster play.");
                LoadVars();
                if (SVN_Checkout_exists(minecraft_update_client_dir))
                {
                    Console.WriteLine("Minecraft Update Program svn update \n", run_Update(minecraft_update_client_dir, Repo_MCU_client));
                    Main_update_function();
                }
                else
                {
                    if (minecraft_update_folder_exist())
                    {
                        run_Checkout(minecraft_update_client_dir, Repo_MCU_client);

                        //run_Update(minecraft_update_client_dir, Repo_MCU_client);
                    }
                    if (SVN_Checkout_exists(minecraft_update_client_dir))
                    {
                        Console.WriteLine( "Minecraft Update Program svn update \n" , run_Update(minecraft_update_client_dir, Repo_MCU_client));
                        Main_update_function();
                    }
                }
                //savevars();

                PopulateServers(); //--------------load server vars? Name IP slots?
            }
            else
            {
                
            }
        }

        private void update_client()
        {
            string update_tool_exe = minecraft_update_client_dir + "/update_tool.exe";

            if (File.Exists(update_tool_exe))
            {
//                Console.WriteLine("Process name: {0}",Process.GetCurrentProcess().ProcessName);
                Process.Start(update_tool_exe, string.Format("-update {0} \"{1}\" \"{2}\" \"{3}\"", "-copy", Convert.ToString(Application.ExecutablePath), minecraft_update_client_exe, Process.GetCurrentProcess().ProcessName));
            Application.Exit();
            }

            //File.Copy(minecraft_update_client_exe, Application.StartupPath + "/MineCraft Update.exe new"); //------------------ Move FileSecurity for update
        }

        private void ShowUpdates()
        {
            FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(Application.ExecutablePath);
            FileVersionInfo myFileVersionInfo_other = FileVersionInfo.GetVersionInfo(minecraft_update_client_exe);
            update_button.Text += string.Format( "to {0}" ,myFileVersionInfo_other.FileVersion);
            update_label.Text += string.Format( "{0} update to {1}" ,myFileVersionInfo.FileVersion, myFileVersionInfo_other.FileVersion);
            update_panel.Visible = true;
        }

        private void PopulateServers()//-=-=-=-=-=-=-=-=-=-=-load server vars? Name IP slots?
        {
            servers.Clear();
            servers.Add("default", serverIP);
            ServerSelection.Items.AddRange(servers.Keys.ToArray());
            ServerSelection.SelectedIndex = 0;
        }

        private void LoadVars()
        {
            string advanced_login_check;
            string fast_start_check;
            DirectoryInfo info;
            info = new DirectoryInfo(settingsDIR);
            username = get_settings_var(UpdateConstants.USERNAME);
            password = get_settings_var(UpdateConstants.PASSWORD);
            advanced_login_check = get_settings_var(UpdateConstants.ADVANCE_LOGIN);
            fast_start_check = get_settings_var(UpdateConstants.QUICK_START);
            if (!IPAddress.TryParse(get_settings_sync_var(UpdateConstants.SERVERIP) ?? string.Empty, out serverIP))
                Console.WriteLine("Server IP was null");

            if (!info.Exists) { Directory.CreateDirectory(settingsDIR); }
            if (username == null)
            {
                Console.WriteLine("Username NULL");
    username = new_settings_save(UpdateConstants.USERNAME, username_box.Text);  } else {
                username_box.Text = username; }
            if (password == null) { 
    password = new_settings_save(UpdateConstants.PASSWORD, password_box.Text);  } else {
                password_box.Text = password; }
            if (password_box.Text != UpdateConstants.PASSWORD) { password_box.UseSystemPasswordChar = true; }
            if (fast_start_check == null) { 
    fast_start.Checked = Convert.ToBoolean(new_settings_save(UpdateConstants.QUICK_START, "false"));  } else {
                fast_start.Checked =  Convert.ToBoolean(fast_start_check); }
            if (advanced_login_check == null) { 
    advanced_login_checkbox.Checked = Convert.ToBoolean(new_settings_save(UpdateConstants.ADVANCE_LOGIN, "false"));  } else {
                advanced_login_checkbox.Checked =  Convert.ToBoolean(advanced_login_check); }

            if (serverIP == null)
            {
            }
            else
            {
                serverlink.Text = "Server IP: " + serverIP;
                serverlink.Visible = true;
            }
        }

        private void savevars()
        {
            if (Minecraft_Exist())
            {
                DirectoryInfo info;
                info = new DirectoryInfo(settingsDIR);

                if (!info.Exists)
                {
                    Directory.CreateDirectory(settingsDIR);
                }
                if (!set_settings_var(UpdateConstants.USERNAME, username))
                {
                    new_settings_save(UpdateConstants.USERNAME, username);
                    Console.WriteLine("username Success");
                }
                if (!set_settings_var(UpdateConstants.PASSWORD, password))
                {
                    new_settings_save(UpdateConstants.PASSWORD, password);
                    Console.WriteLine("password Success");
                }
                if (password_box.Text != UpdateConstants.PASSWORD) { password_box.UseSystemPasswordChar = true; }

                if (!set_settings_var(UpdateConstants.QUICK_START, Convert.ToString(fast_start.Checked)))
                {
                    LoadVars();
                }

                if (!set_settings_var(UpdateConstants.ADVANCE_LOGIN, Convert.ToString(advanced_login_checkbox.Checked)))
                {
                    LoadVars();
                }
            }
            else
            {
                Console.WriteLine("Save Failed");
            }


        }

        public void MainWorker_Progress_Update(object sender, ProgressChangedEventArgs e)
        {
            
        }

        public void MainWork_DoWork(System.Object sender, DoWorkEventArgs e)
        {
            MainWork.ReportProgress(54);
        }

        private Boolean Safety_DIR_Check()
        {
            DirectoryInfo info;
            info = new DirectoryInfo(minecraftDIR);
            if (!info.Exists)
            {
                return false;
            }
            info = new DirectoryInfo(settingsDIR);
            if (!info.Exists)
            {
                return false;
            }
            return false;
        }

        private string get_settings( string filedir )
        {
            try
            {
                string str = "";
                if (checkforsetting(filedir))
                {
                    str = File.ReadAllText(filedir);
                }
                return str;
            }
            catch(IOException e)
            {
                Console.WriteLine("[IOException] get_settings: {0}", e.Message);

                Exception_dialog("[IOException] get_settings: " + e.Message + " from this source " + e.Source);

                return null;
            }

        }

        private string[] get_settings_array(string filedir)
        {
            try
            {
                string[] str_array = { "" };
                if (checkforsetting(filedir))
                {
                    if (File.Exists(filedir))
                    {
                        str_array = File.ReadAllLines(filedir);
                    }
                }

                return str_array;
            }
            catch (IOException e)
            {
                Console.WriteLine("[IOException] get_settings_array: {0}", e.Message);

                Exception_dialog(string.Format("[IOException] get_settings_array: {0}", e.Message));

                return null;
            }
        }

        private Boolean checkforsetting( string filedir )
        {
            try
            {
                if (!Directory.Exists(settingsDIR))
                {
                    Directory.CreateDirectory(settingsDIR);
                }
                if (!File.Exists(filedir))
                {
                    //new FileIOPermission(FileIOPermissionAccess.Read, filedir).Demand();
                    File.WriteAllText(filedir, "");
                }
                return true;
            }
            catch (IOException e)
            {
                Console.WriteLine("[Exception]checkforsettings: {0}" ,e.Message);

                Exception_dialog(string.Format("[Exception]checkforsettings: {0}" ,e.Message));

                //new FileIOPermission(FileIOPermissionAccess.Read, settingsFile).Demand();
                //File.WriteAllText(settingsFile, "");

                return false;
            }
            catch (UnauthorizedAccessException e)
            {
                Console.WriteLine("[UnauthorizedAccessException]checkforsettings: {0}" ,e.Message);

                
                //new FileIOPermission(FileIOPermissionAccess.Read, settingsFile).Demand();
                //File.WriteAllText(settingsFile, "");
                Exception_dialog(string.Format("[UnauthorizedAccessException]checkforsettings: {0}", e.Message));


                return false;
            }
        }

        private string new_settings_save(string varname, string var)
        {
            try
            {
                string str_array = get_settings( settingsFile );
                Console.WriteLine(str_array);
                str_array += Environment.NewLine + varname + "=" + var;
//                str_array += varname + "=" + var;
                File.WriteAllText(settingsFile, str_array);
                return var;
            }
            catch(IOException e)
            {
                Console.WriteLine("[IOException] New_settings_save: \n {0}", e.Message);
                Exception_dialog(string.Format("[IOException] New_settings_save: \n {0}", e.Message));

                return var;
            }
        }

        private Boolean set_settings_var( string VartoChange , string changeTo )
        {
            try
            {
                string[] str_array = get_settings_array(settingsFile);

                if (str_array.Length == 0)
                {
                    Console.WriteLine("set_settings_var: Got a null from get_settings_array");
                    return false;
                }
                else
                {
                    Console.WriteLine(str_array.Length);
                    string line = null;

                    int i = 0;

                    do
                    {
                        if (str_array[i].Contains(VartoChange))
                        {
                            int num = str_array[i].IndexOf("=")+1;
                            Console.WriteLine(str_array[i]);
                            if (str_array[i] != VartoChange + "=")
                            {
                                str_array[i] = str_array[i].Remove(num);
                            }
                            Console.WriteLine(str_array[i]);
                            str_array[i] += changeTo;
                            Console.WriteLine(str_array[i]);
                            line = str_array[i];
                        }

                        i++;
                    }
                    while (str_array.Count() > i);
                    File.WriteAllLines(settingsFile, str_array);
                    Console.WriteLine("New Var Line: {0}", line);
                    if (line != null)
                    {
                        return true;
                    }
                }
                return false;
            }
            catch(IOException e)
            {

                Exception_dialog(string.Format("[IOException] set_settings_var:\n {0}", e.Message));
                //Console.WriteLine("[IOException] set_settings_var:\n {0}", e.Message);
                return false;
            }

            catch (UnauthorizedAccessException e)
            {
                Console.WriteLine("[UnauthorizedAccessException]set_settings_var:\n {0}", e.Message);
                Exception_dialog(string.Format("[UnauthorizedAccessException] set_settings_var:\n {0}", e.Message));

                //new FileIOPermission(FileIOPermissionAccess.Read, settingsFile).Demand();
                //File.WriteAllText(settingsFile, "");

                return false;
            }
        }

        private string get_settings_var( string find_var)
        {
            string[] str_array = get_settings_array( settingsFile );

            string line = null;

            int i = 0;
            if (str_array.Count() != 0)
            {
            do
            {
                if (str_array[i].Contains(find_var))
                {
                    int num = str_array[i].IndexOf("=")+1;
                   // if (str_array[i] != find_var + "=")
                   // {
                        str_array[i] = str_array[i].Remove(0, num);
                   // }
                    line = str_array[i];
                }

                i++;
            }
            while (str_array.Length > i);
            }
            Console.WriteLine("Gotten Var: {0}", line);
            return line;
        }

        private string get_settings_sync_var(string find_var)
        {
            try
            {
                string[] str_array = get_settings_array(settings_sync_File);

                string line = null;

                int i = 0;
                if (str_array.Count() != 0)
                {
                    do
                    {
                        if (str_array[i].Contains(find_var))
                        {
                            int num = str_array[i].IndexOf("=") + 1;
                            // if (str_array[i] != find_var + "=")
                            // {
                            str_array[i] = str_array[i].Remove(0, num);
                            // }
                            line = str_array[i];
                        }

                        i++;
                    }
                    while (str_array.Length > i);
                }
                Console.WriteLine("Gotten Sync Var: {0}", line);
                return line;
            }
            catch (IOException e)
            {
                Console.WriteLine(e.GetBaseException());
                Exception_dialog(string.Format("[IOException] get_settings_sync_var:\n {0}", e.Message));

                return null;
            }
        }

        private void run_minecraft()
        {
            if (File.Exists(minecraft_exe))
            {
                if (advanced_login_checkbox.Checked)
                {
                    if (serverIP != null && Minecraft_Exist())
                    {
                        Util.RunCommand(minecraft_exe + " " + username + " " + password + " " + serverIP);
                        
                        //System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + minecraft_exe + " " + username + " " + password + " " + serverip);

                    }
                    else
                    {
                        Util.RunCommand(minecraft_exe + " " + username + " " + password);
                        //new System.Diagnostics.ProcessStartInfo("cmd", "/c " + minecraft_exe + " " + username + " " + password);
                    }
                }
                else
                {
                    Util.RunCommand(minecraft_exe);
                }
            }
            else
            {
                Console.WriteLine("Minecraft exe not found: {0}" , minecraft_exe);
            }
        }

        private void FindAndChangeFont(RichTextBox ptxtRichTextBox, string pstrFind)
        {
            try
            {
                if (ptxtRichTextBox != null)
                {
                    System.Drawing.Font fntFont = new Font("Verdana", 10f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 178, false);
                    int i = ptxtRichTextBox.Find(pstrFind);
                    int j = pstrFind.Length;
                    ptxtRichTextBox.Select(i, j);
                    ptxtRichTextBox.SelectionFont = fntFont;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void writelog( List<List<string>> ls )
        {
            int i;
            string str = "";
            //Console.WriteLine();
            for( i=0; i < ls[0].Count ;i++) {
//                str += "Revision " + ls[0][i].Remove(0,1);
                log.SelectionFont = new Font("Arial", 10, FontStyle.Bold);
                log.SelectionColor = Color.IndianRed;
                log.SelectedText += "Revision " + ls[0][i].Remove(0, 1) + "\n";
                log.SelectionFont = new Font("Microsoft Sans Serif", 9);
                log.SelectionColor = Color.Black;
                log.SelectedText += ls[1][i] + "\n";

//                str = "";
//                str += "Revision " + ls[0][i].Remove(0,1);
//                str += "\n";
//                str += ls[1][i];
//                ls2.Add(str);
            }
        }

        private List<string> Log_Readable_list( List<List<string>> ls )
        {
            List<string> ls2 = new List<string>();

            //Console.WriteLine(readable_delete2(ls[0]));
            int i;
            string str = "";
            //Console.WriteLine();
            for( i=0; i < ls[0].Count ;i++) {
                str = "";
                str += "Revision " + ls[0][i].Remove(0,1);
                str += "\n";
                str += ls[1][i];
                ls2.Add(str);
            }

            //Console.WriteLine(ls[0][2]);
            //Console.WriteLine(ls[1][2]);

            return ls2;
        }

        private string Log_Readable_string(List<List<string>> ls)
        {
            string str = "";
            int i;
            for (i = 0; i < ls.Count; i++)
            {

                str += ls[i][i] + ls[i][i + 1];
            }

            return str;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            savevars();
            Form1.ActiveForm.Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            switch (selection)
            {
                case 1:
                    //UpdateFunction();


                    Console.WriteLine(run_Update( minecraftDIR, Repo ));

                    break;
                case 2:
                    //CheckoutFunction();
                    statusBar.Text = "Wake up " + Environment.UserName;
                    string s = run_Checkout( minecraftDIR, Repo );
                    Console.WriteLine(s);
                    ConsoleLog(s);//--------------------------------------Log
                    run_Update( minecraftDIR, Repo );
                    statusBar.Text = "The Matix has " + Environment.UserName;
                    break;
                case 3:
                    if(bitquestion) {
                        System.Diagnostics.Process.Start(SVN64);
                    }
                    else {
                        System.Diagnostics.Process.Start(SVN32);
                    }
                    Application.Exit();
                    break;

                case 4:
                    //if( )
                    //{
                    Console.WriteLine("Play");
                    savevars();
                    run_minecraft();
                    //}
                    Application.Exit();
                    break;
                default:
                    Console.WriteLine("Invalid selection. Please select 1, 2, or 3.");
                    break;
            }
        }

        private string run_Checkout( string dir , string repo)
        {
            MainButton.Enabled = false;
            MainButton.ForeColor = Color.DarkGray;
            Console.WriteLine("Repo is : {0} \n Directory is : {1}", repo, dir);
            string s = Util.RunCommandOut("svn checkout --force " + repo + " " + quote + dir + quote );
            MainButton.ForeColor = Color.DeepPink;
            MainButton.Enabled = true;
            MainFunction();
            return s;
        }

        private string run_Update( string dir, string repo )
        {
            MainButton.Enabled = false;
            List<List<string>> cmdreturned = run_command_SVNstatus("svn status " + quote + dir + quote);

            string s = readable_delete2(fixfiles(cmdreturned,  dir, repo));

            MainButton.Enabled = true;

            savevars();
            LoadVars();
            return s;
        }

        public void MainFunction()
        {
            Svn_status = SVN_Exist();
            if (Svn_status)
            {
                if (Minecraft_Exist())
                {
                    if (SVN_Checkout_exists(minecraftDIR))
                    {
                        if (!fast_start.Checked)
                        {
                            MainButton.Text = "Update";
                            say.Text = "Just Click " + MainButton.Text + " to download new revisions.";
                            selection = 1;
                        }
                        else
                        {
                            run_Update( minecraftDIR, Repo );
                            say.Text = "Quick start is Enabled - update has already finished just click." + MainButton.Text + ".";
                        }
                    }
                    else
                    {
                        MainButton.Text = "Checkout";
                        say.Text = "This will edit your minecraft files. If your ok with this please click " + MainButton.Text + ".";
                        selection = 2;
                    }
                }
                else
                {
                    MainButton.Text = "Play";
                    if (minecraft_exe != "" && File.Exists(minecraft_exe))
                    {
                        say.Text = "You are missing mainfiles for Minecraft. \n Clicking " + MainButton.Text + " and I will Attempt to start Minecraft, but you must login to get the necessary files.";
                        selection = 4;
                    }
                    else
                    {
                        MainButton.Enabled = false;
                        say.Text = "You are missing mainfiles for Minecraft \n You need to login to get the necessary files.";
                        selection = 4;
                    }
                }
            }
            else
            {
                say.Text = "You seem to be missing " + SVNName + "\nThis Program uses " + SVNName + " to obtain the minecraft files needed. \n\nPlease click Download for the direct download link. \n If you have already installed " + SVNName + " you might need to restart. ";
                MainButton.Text = "Download";
                selection = 3;
            }

        }

        public Boolean deleteMinecraftFiles(List<string> ls, string dir)
        {
            try
            {
                //Environment.CurrentDirectory = FindMinecraft();
                //DirectoryInfo info = new DirectoryInfo("/bin/minecraft.jar");
                Console.WriteLine("Deleting Files....");
                int i;
                DirectoryInfo info;
                for (i = 0; i < ls.Count; i++)
                {
                    info = new DirectoryInfo(ls[i]);
                    Console.WriteLine(info.FullName);
                    if (File.Exists(ls[i]))
                    {
                        File.Delete(ls[i]);
                        Console.WriteLine("Deleted: [{0}]", ls[i]);
                        ConsoleLog("Deleted: " + ls[i]);//--------------------------------------Log
                    }
                    else
                    {
                        info = new DirectoryInfo(dir + "/.svn");
                        if (info.Exists)
                        {
                            Console.WriteLine("Deleted: SVN Folder");
                            //System.IO.Directory.Delete(info.FullName, true);
                            //DeleteSubFolders(@minecraftDIR, ".svn", true);
                        }
                        else
                        {
                            Console.WriteLine("Deleted: Failed");
                        }

                        //ConsoleLog("Deleted: SVN Folder");//--------------------------------------Log
                        //ConsoleLog(info.FullName);//--------------------------------------Log
                        Console.WriteLine("[{0}] Does Not Exist", ls[i]);
                        //run_Checkout();
                        //ConsoleLog("["+ ls[i] + "] Does Not Exist");//--------------------------------------Log
                    }
                }
                Console.WriteLine("Done.");
                return true;
            }
            catch(IOException e)
            {
//                Console.WriteLine("Minecraft inuse Source : {0}" );
                List<string> listofbadfiles = new List<string>();
                int i;
                DirectoryInfo info;
                for (i = 0; i < ls.Count; i++)
                {
                    info = new DirectoryInfo(ls[i]);
                    if(IsFileLocked( new FileInfo(info.FullName))){
                        listofbadfiles.Add(info.FullName);
                    }
                }
                if (delete_files_fail(listofbadfiles))
                {
                    deleteMinecraftFiles(ls, dir);
                }
                return false;
            }
        }

        public void ConsoleLog(string str)
        {
            //log.Text += String.Format( str );
            log.SelectionFont = new Font("Microsoft Sans Serif", 9);
            log.SelectionColor = Color.Black;
            log.SelectedText = String.Format( "{0}\n" , str );
        }

        public static void DeleteSubFolders(string folderPath, string wildcardPattern, bool top)
        {
            try
            {
                String[] list;

                //If we are at the top level, get all directory names that match the pattern
                if (top)
                    list = Directory.GetDirectories(folderPath, wildcardPattern, SearchOption.AllDirectories);
                else //Get directories and files for matching sub directories
                    list = Directory.GetFileSystemEntries(folderPath, wildcardPattern);

                foreach (string item in list)
                {
                    //Sub directories
                    if (Directory.Exists(item))
                    {
                        //Match all sub directories
                        DeleteSubFolders(item, "*", false);
                    }
                    else // Files in directory
                    {
                        //Get the attribute for the file
                        FileAttributes fileAtts = File.GetAttributes(item);
                        //If it is read only make it writable
                        if ((fileAtts & FileAttributes.ReadOnly) != 0)
                        {
                            File.SetAttributes(item, fileAtts & ~FileAttributes.ReadOnly);
                        }
                        File.Delete(item);
                    }
                }
                //Delete the matching folder that we are in
                if (top == false)
                {
                    Directory.Delete(folderPath);
                }
            }
            catch(IOException e)
            {
                Exception_dialog("[IOException]DeleteSubFolders " + e.Message + " came from " + e.Source);
            }
        }

        public List<string> fixfiles(List<List<string>> thelistofbadfiles, string dir, string repo) 
        {

            List<string> str_msg = new List<string>();


            Console.WriteLine("main thread: Starting worker thread...");


            Console.WriteLine(readable_delete2(thelistofbadfiles[1]));

           if (thelistofbadfiles != null)
           {
               List<string> List_of_Folders = readable_FolderList(thelistofbadfiles[1]); //---------- 

               //Console.WriteLine(readable_delete(thelistofbadfiles[1]));
               if (true)
               {
                   List<string> deletion_files = new List<string>() ;
                   List<string> missing_Files = new List<string>();
                   List<string> Modified_Files = new List<string>();
                   List<string> Unknown_Files = new List<string>();
                   List<string> add_Files = new List<string>();
                   List<string> Question_Mark_Files = new List<string>();

                   int i = 0;
                   foreach( string item in thelistofbadfiles[0])
                   {
                       
                       if(item == "!") {
                           missing_Files.Add(thelistofbadfiles[1][i]);
                           Console.WriteLine("Modified: {0}", thelistofbadfiles[1][i]);
                           //ConsoleLog("Missing: " + thelistofbadfiles[1][i]);//--------------------------------------Log
                           str_msg.Add("\nMissing: " + thelistofbadfiles[1][i]);//--------------------------------------Log
                       }
                       else if (item == "M")
                       {
                           Modified_Files.Add(thelistofbadfiles[1][i]);

                           Console.WriteLine( "Modified: {0}" ,thelistofbadfiles[1][i]);
                           //ConsoleLog("Modified: " + thelistofbadfiles[1][i]);//--------------------------------------Log
                           str_msg.Add("\nModified: " + thelistofbadfiles[1][i]);//--------------------------------------Log
                       }
                       else if (item == "D")
                       {
                           deletion_files.Add(thelistofbadfiles[1][i]);

                           Console.WriteLine("Deletion: {0}", thelistofbadfiles[1][i]);
                           //ConsoleLog("Deletion: " + thelistofbadfiles[1][i]);//--------------------------------------Log
                           str_msg.Add("Deletion: " + thelistofbadfiles[1][i]);//--------------------------------------Log
                       }
                       else if (item == "A")
                       {
                           add_Files.Add(thelistofbadfiles[1][i]);

                           Console.WriteLine("Add: {0}", thelistofbadfiles[1][i]);
                           //ConsoleLog("Add: " + thelistofbadfiles[1][i]);//--------------------------------------Log
                           str_msg.Add("\nAdd: " + thelistofbadfiles[1][i]);//--------------------------------------Log
                       }
                       else if (item == "?" && List_of_Folders[i] == "mods")
                       {
                           Question_Mark_Files.Add(thelistofbadfiles[1][i]);

                           Console.WriteLine("Add: {0}", thelistofbadfiles[1][i]);
                           //ConsoleLog("Add: " + thelistofbadfiles[1][i]);//--------------------------------------Log
                           str_msg.Add("\nAdd: " + thelistofbadfiles[1][i]);//--------------------------------------Log
                       }
                       //Console.WriteLine(thelistofbadfiles[1]);
                       i++;
                   }
                   if (Question_Mark_Files.Count != 0)
                   {
                       if (delete_files_consent_othermods(Question_Mark_Files))
                       {
                           if (deleteMinecraftFiles(Question_Mark_Files, dir))
                           {
                               Console.WriteLine("Deleted: potential conflicting files.");
  //                             string a = RunCommandOut("svn update " + dir);
//                               Console.WriteLine(a);
//                               string s = (a);//--------------------------------------Log
                               //ConsoleLog(s);//--------------------------------------Log
                               //str_msg.Add(s)

                           }
                       }
                   }

                   if (Modified_Files.Count != 0 | deletion_files.Count != 0 | add_Files.Count != 0)
                   {
                       deletion_files.AddRange(Modified_Files);
                       deletion_files.AddRange(add_Files);
                       if (delete_files_consent(deletion_files))
                       {
                           if (deleteMinecraftFiles(deletion_files, dir))
                           {
                               Console.WriteLine("Deleted: SVN Folder");
                               //System.IO.Directory.Delete(info.FullName, true);
                               DeleteSubFolders(@dir, ".svn", true);
                               run_Checkout(dir, repo);
                               //DeleteSubFolders(@minecraftDIR, ".svn", true);
                               //run_Checkout();
                               string a = Util.RunCommandOut("svn update " + dir);
                               Console.WriteLine(a);
                               string s = (a);//--------------------------------------Log
                               //ConsoleLog(s);//--------------------------------------Log
                               //str_msg.Add(s)

                           }
                           else
                           {
                               MainButton.Text = "Redo Update";
                               return str_msg;
                           }
                       }
                   }
                   else
                   {
                       //ConsoleLog("Already Up to Date");//--------------------------------------Log
                       str_msg.Add("Already Up to Date");//--------------------------------------Log
                       string s = Util.RunCommandOut("svn update " + dir);
                       Console.WriteLine(s);
                       //ConsoleLog(s);//--------------------------------------Log
                       str_msg.Add(s);//--------------------------------------Log
                       selection = 4;
                       MainButton.Text = "Play";
                       return str_msg;
                   }
               }
           }
           else
           {
               MainButton.Text = "Play";
               selection = 4;
               Console.WriteLine("The List of bad files didnt get anything");
               //ConsoleLog("No Files need to be Replace");//--------------------------------------Log
               //ConsoleLog("Up to Date :D");//--------------------------------------Log
               str_msg.Add("No Files need to be Replace");//--------------------------------------Log
               str_msg.Add("Up to Date :D");//--------------------------------------Log
           }

            //string str = Console.ReadLine();
            //int i;
            //for (i=0; Console.;i++ )
            //{
              
            //}

           return str_msg;
        }

        public string readable_delete2(List<string> ls)
        {
            string str = "";
            int i;
            for( i=0; i < ls.Count ;i++) {
                str += ls[i] + "\n";
            }

            return str;
        }

        public string readable_delete(List<string> ls)
        {
            string str = "";
            int i;
            for (i = 0; i < ls.Count; i++)
            {
                str += ls[i].Split('\\').Last() +"\n";
            }

            return str;
        }

        public List<string> readable_FolderList(List<string> ls)
        {
            List<string> str = new List<string>();
            int i;
            for (i = 0; i < ls.Count; i++)
            {
//                Console.WriteLine("Folder Readable log Check : {0}", ls[0]);
                String[] lst = ls[i].Split('\\');
//                Console.WriteLine("Folder Readable log : {0}", lst[i]);
                str.Add (lst.ElementAt(lst.Count() - 2));
            }
            return str;
        }

        protected virtual bool IsFileLocked(FileInfo file)
        {
            FileStream stream = null;

            try
            {
                stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
            }
            catch (IOException)
            {
                //the file is unavailable because it is:
                //still being written to
                //or being processed by another thread
                //or does not exist (has already been processed)
                return true;
            }
            finally
            {
                if (stream != null)
                    stream.Close();
            }

            //file is not locked
            return false;
        }

        //----------------------------------------------- Dialogs

        public Boolean delete_files_consent( List<string> ls )
        {
            // Display a message box asking users if they
            // want to exit the application.
            if (MessageBox.Show("The Following Files will be deleted\n" + readable_delete(ls), "Delete?",
                  MessageBoxButtons.OKCancel, MessageBoxIcon.Question)
                  == DialogResult.OK)
            {
                return true;
            }
            else
            {
                return false;
            }

        }

        public Boolean delete_files_consent_othermods(List<string> ls)
        {
            // Display a message box asking users if they
            // want to exit the application.
            if (MessageBox.Show("The Following Files may not be compatible and will need to be deleted\nWould you like to delete the [Yes Recommended] \n\n" + readable_delete(ls), "Delete?",
                  MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                  == DialogResult.Yes)
            {
                return true;
            }
            else
            {
                return false;
            }

        }

        public Boolean delete_files_fail(List<string> ls)
        {
            // Display a message box asking users if they
            // want to exit the application.
            if (MessageBox.Show("The Following Files seem to be in use. \n Please close them then click Retry else cancel.\n" + readable_delete(ls), "Files inuse?",
                  MessageBoxButtons.RetryCancel, MessageBoxIcon.Question)
                  == DialogResult.Retry)
            {
                return true;
            }
            else
            {
                return false;
            }

        }

//        public static Boolean Exception_dialog(string mainstring , string error, string error2)
        public static Boolean Exception_dialog(string mainstring)
        {
            // Display a message box asking users if they
            // want to exit the application.
//            if (MessageBox.Show("The Following is a Error please give it to Jessica\n" + String.Format(mainstring , error, error2), "ERROR",
            if (MessageBox.Show("The Following is a Error please give it to Jessica\n" + mainstring, "ERROR",
                  MessageBoxButtons.OK, MessageBoxIcon.Error)
                  == DialogResult.OK)
            {
                return true;
            }
            else
            {
                return false;
            }

        }

        //----------------------------------------------- [end] Dialogs

        private void Exception_Do_somthing(Exception e)
        {
            //if (e.GetBaseException != IOException)
            //{

            //}
        }

        public Boolean SVN_Exist(  )
        {
                statusBar.Text = "Wake up " + Environment.UserName;
                //ConsoleLog("MineCraft Data Found");//--------------------------------------Log
                //DirectoryInfo info = new DirectoryInfo(FindMinecraft() + "/.svn");
                osname.Text = Application.CompanyName;
                string str = Util.RunCommandOut("svn help");
//                Console.WriteLine(str);
                if(str != null && str.Length > 4 ) {
                    if (str.Substring(0,5).ToLower() == "usage")
                    {
                        //ConsoleLog("MineCraft Directory: " + minecraftDIR);//--------------------------------------Log
                        Console.WriteLine("MineCraft Directory: " + minecraftDIR);
                        //ConsoleLog("SVN Installed");
                        Console.WriteLine("SVN Installed");
                        return true;
                    }
                    ConsoleLog("SVN Not Installed");
                    return false;
                }
                //ConsoleLog(FindMinecraft());//--------------------------------------Log
                //if(info.Exists) {
                //    return true;
                //}
                return false;
        }

        public Boolean Minecraft_Exist()
        {
            if(FindMinecraft() != null)
            {
                minecraftDIR = FindMinecraft();
                return true;
            }
            else
            {
                //statusBar.Text = "MineCraft Data Missing....";
                //ConsoleLog("MineCraft Data Missing....");//--------------------------------------Log
            }
            return false;
        }

        public Boolean minecraft_update_folder_exist()
        {
            if (Find_minecraft_update_folder())
            {
                DirectoryInfo info;
                Environment.CurrentDirectory = Environment.GetEnvironmentVariable("appdata");
                info = new DirectoryInfo("./.minecraft_update_client");

//                Console.WriteLine("The path to update folder: {0}", minecraft_update_client_dir);
//                DirectoryInfo info = new DirectoryInfo(minecraft_update_client_dir);
                Console.WriteLine("The path to update folder: {0}", info.FullName);
                if (Find_minecraft_update_folder() && info.Exists)
                {
                    return true;
                }
            }
            else
            {
                return false;
            }

            return false;
        }

        public Boolean Find_minecraft_update_folder()
        {
            DirectoryInfo info;
            Environment.CurrentDirectory = Environment.GetEnvironmentVariable("appdata");
            info = new DirectoryInfo("./.minecraft_update_client");
            if (!info.Exists)
            {
                Directory.CreateDirectory(info.FullName);
                minecraft_update_client_dir = info.FullName;
            }
            else minecraft_update_client_dir = info.FullName;

            return true;
        }

        public string FindMinecraft()
        {
            DirectoryInfo info;
            Environment.CurrentDirectory = Environment.GetEnvironmentVariable("appdata");
            info = new DirectoryInfo("./.minecraft");
            //info = new DirectoryInfo("C:/test");
            if (info.Exists)
            {
                minecraftDIR = info.FullName;
                return info.FullName;
            }
            else
            {
                //advanced_login_checkbox.Checked = false;
                //say.Text = "You are missing mainfiles for Minecraft \n Attempting to start Minecraft to get files.";
                //run_minecraft();
            }
                return null;
        }

        public Boolean SVN_Checkout_exists(string dir)
        {
            DirectoryInfo info;
            info = new DirectoryInfo(dir + "/.svn");
            //info = new DirectoryInfo("C:/test");
            if (info.Exists)
            {
                //minecraftDIR = info.FullName;
                return true;
            }
            return false;
        }

        /*public void Worker_Complete_function(MyObject myobject)
        {
            switch (myobject.ACTION)
            {
                case 1:
                    //FixFiles


                    break;
                case 2:
                    //Run CMD Command do something
                    if(myobject.Console_Post_Bool)
                    {
                        Console.WriteLine(myobject.Console_Post_Header);
                        Console.WriteLine(myobject.Console_Post_MSG);
                        ConsoleLog(myobject.Console_Post_Header);
                        ConsoleLog(myobject.Console_Post_MSG);
                    }
                    break;
                default:
                    

                    break;
            }
        }*/

        public List<string> run_command_status(object command)
        {
            try
            {
                // create the ProcessStartInfo using "cmd" as the program to be run,
                // and "/c " as the parameters.
                // Incidentally, /c tells cmd that we want it to execute the command that follows,
                // and then exit.
                System.Diagnostics.ProcessStartInfo procStartInfo =
                    new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);

                // The following commands are needed to redirect the standard output.
                // This means that it will be redirected to the Process.StandardOutput StreamReader.
                procStartInfo.RedirectStandardOutput = true;
                procStartInfo.UseShellExecute = false;
                // Do not create the black window.
                procStartInfo.CreateNoWindow = true;
                // Now we create a process, assign its ProcessStartInfo and start it
                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.StartInfo = procStartInfo;
                proc.Start();
                // Get the output into a string
                string str = null;
                string line = null;
                List<string> lst = null;
                do
                {
 //                   Console.WriteLine("Readline");
                    //Console.WriteLine(proc.StandardOutput.ReadToEnd());
 //                   Console.WriteLine(proc.StandardOutput.EndOfStream);
                    if (!proc.StandardOutput.EndOfStream)
                    {
                        line = proc.StandardOutput.ReadLine();
                        if (line != null)
                        {
                            str = SvnStatus.FindFiles2(line);
                        }
                        else
                        {
                            str = null;
                        }

                        if (str != null && str != "blah")
                        {
//                            Console.WriteLine("returned" + str);
                            lst.Add(str);
                        }
                    }
                    else
                    {
//                        Console.WriteLine("No Lines to read" );
                    }
                }
                while (str != null);

                //proc.StandardOutput.ReadLine
                //string result = proc.StandardOutput.ReadToEnd();
                // Display the command output.
                //Console.WriteLine(str);
                return lst;
            }
            catch (Exception objException)
            {
                // Log the exception
                Console.WriteLine(objException.Message + "ERROR");
                ConsoleLog("FUUUUUUUUUUUUUUUUUUUUU Freaking Crased");//--------------------------------------Log
                ConsoleLog("Notify me that the run_command_status Failed and the error is [" + objException.Message + "]");//--------------------------------------Log
            }
            Console.WriteLine("returned Null");
            return null;
        }

        public List<List<string>> run_command_SVNstatus(object command)
        {
            try
            {
                // create the ProcessStartInfo using "cmd" as the program to be run,
                // and "/c " as the parameters.
                // Incidentally, /c tells cmd that we want it to execute the command that follows,
                // and then exit.
                System.Diagnostics.ProcessStartInfo procStartInfo =
                    new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);

                // The following commands are needed to redirect the standard output.
                // This means that it will be redirected to the Process.StandardOutput StreamReader.
                procStartInfo.RedirectStandardOutput = true;
                procStartInfo.UseShellExecute = false;
                // Do not create the black window.
                procStartInfo.CreateNoWindow = true;
                // Now we create a process, assign its ProcessStartInfo and start it
                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.StartInfo = procStartInfo;
                proc.Start();
                // Get the output into a string
                List<string> ls = new List<string>();
                List<string> ls2 = new List<string>();
                List<string> incomelist = null;
                string line  = null;
                List<List<string>> Mainlst = new List<List<string>>();
                do
                {
//                    Console.WriteLine("Readline");
                    //Console.WriteLine(proc.StandardOutput.ReadToEnd());
//                    Console.WriteLine(proc.StandardOutput.EndOfStream);
                    if (!proc.StandardOutput.EndOfStream)
                    {
                        line = proc.StandardOutput.ReadLine();
                        if (line != null)
                        {
                            incomelist = SvnStatus.FindFiles(line);
                        }
                        else
                        {
                            incomelist = null;
//                            Console.WriteLine("Income Null ");
                        }

                        if (incomelist != null && incomelist[0] != "b")
                        {
//                            Console.WriteLine("returned: " + incomelist[1]);
                            ls.Add(incomelist[0]);
                            ls2.Add(incomelist[1]);
//                            Console.WriteLine("passed");
                        }
                    }
                    else
                    {
//                        Console.WriteLine("No Lines to read");
                    }
                }
                while (!proc.StandardOutput.EndOfStream);

                //proc.StandardOutput.ReadLine
                //string result = proc.StandardOutput.ReadToEnd();
                // Display the command output.
                //Console.WriteLine(str);
                Mainlst.Add(ls);
                Mainlst.Add(ls2);
                return Mainlst;
            }
            catch (Exception objException)
            {
                // Log the exception
                Console.WriteLine(objException.Message + "ERROR");
                ConsoleLog("FUUUUUUUUUUUUUUUUUUUUU Freaking Crased");//--------------------------------------Log
                ConsoleLog("Notify me that the run_command_status Failed and the error is [" + objException.Message + "]");//--------------------------------------Log
            }
            Console.WriteLine("returned Null");
            return null;
        }

        public List<List<string>> run_command_SVNlog(object command)
        {
            try
            {
                // create the ProcessStartInfo using "cmd" as the program to be run,
                // and "/c " as the parameters.
                // Incidentally, /c tells cmd that we want it to execute the command that follows,
                // and then exit.
                System.Diagnostics.ProcessStartInfo procStartInfo =
                    new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);

                // The following commands are needed to redirect the standard output.
                // This means that it will be redirected to the Process.StandardOutput StreamReader.
                procStartInfo.RedirectStandardOutput = true;
                procStartInfo.UseShellExecute = false;
                // Do not create the black window.
                procStartInfo.CreateNoWindow = true;
                // Now we create a process, assign its ProcessStartInfo and start it
                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.StartInfo = procStartInfo;
                proc.Start();
                // Get the output into a string
                List<string> ls = new List<string>(); // Rev
                List<string> ls2 = new List<string>(); // Updates
                List<string> incomelist = null;
                string line = null;
                Boolean go = true;
                
                List<List<string>> Mainlst = new List<List<string>>();
                do
                {
                    //Console.WriteLine("Readline");
                    //Console.WriteLine(proc.StandardOutput.ReadToEnd());
                    //Console.WriteLine(proc.StandardOutput.EndOfStream);
                    if (!proc.StandardOutput.EndOfStream)
                    {
                        line = proc.StandardOutput.ReadLine();
                        if (line != null)
                        {
                            if(line.StartsWith("-")) {
                                //Console.WriteLine("Found ---------------");
                                line = proc.StandardOutput.ReadLine();
                                if (line.StartsWith("r"))
                                {
                                    incomelist = line.Split('|').ToList<string>();

                                    

                                    //Console.WriteLine("IcomeList: " + incomelist[3]);



                                    if (incomelist[3].Substring(3, 4) == "line")
                                    {
//                                        Console.WriteLine("FOUND the word line");
                                        ls.Add( incomelist[0].Trim());
                                        int i;
                                        string str2 = "";
                                        line = proc.StandardOutput.ReadLine();
//                                        Console.WriteLine("Blank: " + line);
                                        for (i = 0; i < Convert.ToInt32( incomelist[3].Substring(1, 1)); i++)
                                        {
                                            line = proc.StandardOutput.ReadLine();
 //                                           Console.WriteLine("Line Saved:" + line);
                                            str2 += line.Trim() + "\n";
                                        }
                                        ls2.Add(str2.Trim() + "\n");
                                        //Console.WriteLine(str2);
                                    }
                                    else
                                    {
                                        //Console.WriteLine("Could Not FOUND the word line");
                                    }
                                }
                                else
                                {
                                    //Console.WriteLine("r not found: " + line);
                                }
                            }
                            //incomelist = svnstatus.findfiles(line);
                        }
                        else
                        {
                            //incomelist = null;
//                           Console.WriteLine("Income Null ");
                        }

                        if (incomelist != null && incomelist[0] != "b")
                        {
                            //Console.WriteLine("returned: " + incomelist[1]);
                            //ls.Add(incomelist[0]);
                            //ls2.Add(incomelist[1]);
//                            Console.WriteLine("passed");
                        }
                    }
                    else
                    {
//                        Console.WriteLine("No Lines to read");
                    }
                    if(ls.Count() > 5)
                    {
                        go = false;
                    }
                }
                while (!proc.StandardOutput.EndOfStream && go);

                //proc.StandardOutput.ReadLine
                //string result = proc.StandardOutput.ReadToEnd();
                // Display the command output.
                //Console.WriteLine(str);
                Mainlst.Add(ls);
                Mainlst.Add(ls2);
                return Mainlst;
            }
            catch (Exception objException)
            {
                // Log the exception
                Console.WriteLine(objException.Message + "ERROR");
                ConsoleLog("FUUUUUUUUUUUUUUUUUUUUU Freaking Crashed");//--------------------------------------Log
                ConsoleLog("Notify me that the run_command_status Failed and the error is [" + objException.Message + "]");//--------------------------------------Log
            }
            Console.WriteLine("returned Null");
            return null;
        }

        private void backgroundWorker1_DoWork(System.Object sender, DoWorkEventArgs e)
        {
            MyObject myobject = (MyObject)e.Argument;
            string str = "";

            switch (myobject.ActionFunction)
            {
                case 1:
                    List<List<string>> cmdreturned = run_command_SVNstatus("svn status " + minecraftDIR);

                    //                    str += fixfiles(cmdreturned);


                    break;

                case 2:

                    str += Util.RunCommandOut(myobject.ConsoleCommand);

                    break;

                default:

                    break;

            }

            //MyObject myobject = (MyObject)sender;

            /*if (myobject.Console_Post_Bool)
            {
                switch (myobject.ACTION)
                {
                    case 1:
                        //FixFiles


                        break;
                    case 2:
                        //Run CMD Command do something
                        if (myobject.Console_Post_Bool)
                        {
                            Console.WriteLine(myobject.Console_Post_Header);
                            Console.WriteLine(myobject.Console_Post_MSG);

                            //log.Text = "nom";
                            //ConsoleLog(myobject.Console_Post_Header);
                            //ConsoleLog(myobject.Console_Post_MSG);
                        }

                        break;
                    default:

                        //Worker_Complete_function(myobject);

                        break;
                }
            }*/

            if (myobject.ConsolePostBool)
            {
                log.Text += "\n" + str;
            }
        }



        private void password_box_TextChanged(object sender, EventArgs e)
        {
            password_box.UseSystemPasswordChar = password_box.Text != "password";
        }

        private void advanced_login_checkbox_CheckedChanged(object sender, EventArgs e)
        {
            advanced_login_panel.Visible = advanced_login_checkbox.Checked;
        }

        private void serverlink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://www.gametracker.com/server_info/" + serverIP + "/");
        }

        private void update_button_Click(object sender, EventArgs e)
        {
            update_client();
        }
    }
}
